import axios from 'axios'
import router from '../router/index'
import { Loading, Message } from "element-ui";
import {httpBaseUrl} from './globa'

const http = axios.create({
    baseURL: httpBaseUrl,
    timeout: 10000,
    responseType: 'json'
})

const msg = []

http.interceptors.request.use(config => {
    msg.push(Loading.service({
        text: '加载中...',
        fullscreen: true
    }));
    config.headers['Authorization'] = `Bearer ${sessionStorage.getItem('token')}`
    return config
})

http.interceptors.response.use(res => {
    if(msg.length) msg.pop().close()
    if (res.status === 200) {
        if (res.data.code === 401) {
            Message.error({
                content: res.data.msg,
                duration: 1,
                onClose: () => router.replace('/login')
            })
        } else if (res.data.code === 402) Message.error('你当前没有权限访问该模块！')
        else if (res.data.code === 500) Message.error('服务器错误，请联系管理员')
        else if (res.data.code === 400) Message.error(res.data.msg)
        return res.data
    } else {
        Message.error('服务器错误，请联系管理员')
    }
}, err => {
    if(msg.length) msg.pop().close()
    if (err.message.indexOf('401') > -1) {
        Message.error({
            content: '页面未找到',
            duration: 1,
            onClose: () => router.replace('/login')
        })
        return;
    }
    console.log(err);
    Message.error(err)
})

export default http
